import datetime
import random
import threading
import time

from connection import PhoenixConnect

conn: PhoenixConnect

done = 0
index = 0


def current_milli():
    return int(round(time.time() * 1000))


def get_date_list(days):
    """返回前days天日期列表"""
    date_list = list()
    for i in range(0, days):
        day = datetime.datetime.now() - datetime.timedelta(days=i)
        date_to = datetime.datetime(day.year, day.month, day.day).strftime('%Y-%m-%d')
        date_list.append(date_to)
    return date_list


# 最近7天日期list
data_list = get_date_list(7)

# 最近7天开始以及结束时间戳
time_list = [current_milli() - 604800000, current_milli()]


class DataCreator:
    conn = None
    cursor = None
    tid: int
    start: int
    end: int

    def __init__(self, url, tid, start, end):
        self.conn = PhoenixConnect(url)
        self.cursor = self.conn.get_update_cursor()
        self.tid = tid
        self.start = start
        self.end = end

    def exec_updates(self, sqls):
        try:
            for sql in sqls:
                # print(sql)
                self.cursor.execute(sql)
        except Exception as ex:
            print(ex)

    def select(self, sql):
        return self.conn.select(sql)

    # 创建用户信息数据
    def create_user_data(self):
        global done
        print('Thread %d started...' % self.tid)

        try:
            for i in range(self.start, self.end + 1):
                uid = i
                sqls = []
                name = 'name_%d' % i
                next_count_date = random.choice(data_list)
                sql = "UPSERT INTO GE.USER_GE(UID, NAME, STATUS, NEXT_COUNT_DATE) " \
                      "VALUES(%d, '%s', '%s', '%s')" % (uid, name, "NORMAL", next_count_date)
                sqls.append(sql)
                self.exec_updates(sqls)
        except Exception as ex:
            print('%d号线程异常：' % self.tid)
            print(ex)

        done = done + 1

    #  创建用户位置信息数据
    def create_position_data(self):
        global done
        global index
        print('Thread %d started...' % self.tid)

        try:
            for i in range(self.start, self.end + 1):
                sqls = []
                uid = i
                # 每个用户随机5-10个位置
                for j in range(1, random.randint(5, 10)):
                    coord = Coord(round(random.uniform(coord1.x, coord2.x), 6),
                                  round(random.uniform(coord2.y, coord1.y), 6))
                    index += 1
                    create_ts = random.uniform(time_list[0], time_list[1])
                    sql = "UPSERT INTO GE.USER_POSITION(" \
                          "ID, UID, CREATE_TS, POSITION, CELL_ID) " \
                          "VALUES(%d, %d, %d, '%s', 0)" % (index, uid, create_ts, coord.get_value())

                    sqls.append(sql)

                self.exec_updates(sqls)
        except Exception as ex:
            print('%d号线程异常：' % self.tid)
            print(ex)

        done = done + 1


class Coord(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_value(self):
        return '{\"x\": %f,\"y\": %f}' % (self.x, self.y)


# 范围为武汉市地图坐标（114.168256,30.731558） - （114.632225,30.337035）
coord1 = Coord(114.168256, 30.731558)
coord2 = Coord(114.632225, 30.337035)

if __name__ == '__main__':
    # 武汉地图大概50*50 km^2 可以初始化2500个格子
    # 假设平均每个格子20个人 需要创建50000个用户
    # 假设每个用户上传10次位置

    url = 'http://mng1:8765/'

    # 创建 50000 个用户信息
    count = 200;
    # 每个进程处理数量
    batch = 50;

    # 生成位置数据
    for i in range(count // batch):
        dc = DataCreator(url, i + 1, 1 + batch * i, batch * (i + 1))
        t = threading.Thread(target=dc.create_position_data, args=())
        t.start()
    # 生成用户数据
    for i in range(count // batch):
        dc = DataCreator(url, i + 1, 1 + batch * i, batch * (i + 1))
        t = threading.Thread(target=dc.create_user_data, args=())
        t.start()

    # while done < 5:
    #     print("index: %d" % index)
    #     time.sleep(1)
